package com.string.actortv.service;

import android.app.Application;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.*;
import android.util.Log;
import android.widget.Toast;
import androidx.core.content.FileProvider;
import com.string.actortv.APPApplication;
import com.string.actortv.R;
import com.string.actortv.dto.UpdateInformation;
import com.string.actortv.util.DownloadUtil;

import java.io.File;
import java.io.IOException;

/**
 * 不要忘记注册，在mainfest文件中
 */
public class UpdateService extends Service {
    private DownLoadBinder downLoadBinder = new DownLoadBinder();

    // BT字节参考量
    private static final float SIZE_BT = 1024L;
    // KB字节参考量
    private static final float SIZE_KB = SIZE_BT * 1024.0f;
    // MB字节参考量
    private static final float SIZE_MB = SIZE_KB * 1024.0f;

    private final static int DOWNLOAD_COMPLETE = 1;// 完成
    private final static int DOWNLOAD_NOMEMORY = -1;// 内存异常
    private final static int DOWNLOAD_FAIL = -2;// 失败

    private String appName = null;// 应用名字
    private String appUrl = null;// 应用升级地址
    private int forceFlag = 0;// 强制升级标识，1--不强制，2--强制

    private Intent updateIntent = null;// 下载完成

    public void setServiceCallback(ServiceCallback serviceCallback) {
        this.serviceCallback = serviceCallback;
    }

    private ServiceCallback serviceCallback;

    public interface ServiceCallback {
        void setCurrentValue(int num);

        void dismissDialog();
    }

    /**
     * 内部类继承Binder
     *
     * @author lenovo
     */
    public class DownLoadBinder extends Binder {
        /**
         * 声明方法返回值是MyService本身
         *
         * @return
         */
        public UpdateService getService() {
            return UpdateService.this;
        }
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return downLoadBinder;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        appName = intent.getStringExtra("appname");
        appUrl = intent.getStringExtra("appurl");
        forceFlag = intent.getIntExtra("forceFlag", 2);
        updateIntent = new Intent(this, APPApplication.class);
        PendingIntent.getActivity(this, 0, updateIntent,
                0);
        new UpdateThread().execute();
    }

    /**
     * 下载更新程序文件
     *
     * @param downloadUrl 下载地址
     * @return
     */
    private int downloadUpdateFile(String downloadUrl) {
        Application context = APPApplication.getInstance();
        File updateDir;
        if (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())) {
            updateDir = new File(Environment.getExternalStorageDirectory(),
                    UpdateInformation.downloadDir);
        } else {
            updateDir = context.getFilesDir();
        }
        Log.d("AutoUpdate", "开始下载");
        DownloadUtil.get().download(downloadUrl, updateDir.getPath(),
                APPApplication.getInstance().getResources()
                        .getString(R.string.app_name) + ".apk",
                new DownloadUtil.OnDownloadListener() {
                    @Override
                    public void onDownloadSuccess(File file) {
                        serviceCallback.dismissDialog();
                        Log.d("AutoUpdate", "下载成功");
                        String cmd = "chmod 777 " + file.getPath();
                        try {
                            Runtime.getRuntime().exec(cmd);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        Uri uri = Uri.fromFile(file);
                        //安装程序
                        Intent installIntent = new Intent(Intent.ACTION_VIEW);
                        installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            installIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            uri = FileProvider.getUriForFile(UpdateService.this, UpdateService.this.getPackageName() + ".fileprovider", file);
                        }
                        installIntent.setDataAndType(uri, "application/vnd.android.package-archive");
                        PendingIntent.getActivity(
                                UpdateService.this, 0, installIntent, 0);
                        //启动安装程序
                        UpdateService.this.startActivity(installIntent);
                    }

                    @Override
                    public void onDownloading(int progress) {
                        serviceCallback.setCurrentValue(progress);
                    }

                    @Override
                    public void onDownloadFailed(Exception e) {
                        Log.e("AutoUpdate", "下载失败:" + e.getMessage());
                        Looper.prepare();
                        Toast.makeText(getApplicationContext(), "下载失败", Toast.LENGTH_SHORT).show();
                        Looper.loop();
                        if (forceFlag == 2) {
                            // 直接退出应用
                            System.exit(0);
                        }
                    }

                });
        return DOWNLOAD_COMPLETE;
    }

    /**
     * 在这里使用了asynctask异步任务来下载
     */
    class UpdateThread extends AsyncTask<Void, Void, Integer> {
        @Override
        protected Integer doInBackground(Void... params) {
            return downloadUpdateFile(appUrl);
        }

        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);
            stopSelf();
        }

    }

}
